package com.example.onlineeducation.ui.main

import android.content.Context
import android.content.Intent
import android.text.Editable
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.example.onlineeducation.R
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.TopicType
import com.example.onlineeducation.data.db.datastore.UserInfoDataStoreKey
import com.example.onlineeducation.data.db.room.RoomData
import com.example.onlineeducation.data.db.room.SearchHistoryDao
import com.example.onlineeducation.data.db.room.SearchHistoryTable
import com.example.onlineeducation.databinding.HomeSearchActivityBinding
import com.example.onlineeducation.viewmodel.MainHomeVM
import com.example.onlineeducation.widget.flowlayout.FlowLayout
import com.example.onlineeducation.widget.flowlayout.TagAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.yc.jetpacklib.extension.ycIsNotEmpty
import com.yc.jetpacklib.extension.ycToNoEmpty
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.recycleView.YcViewPagerAdapter
import com.yc.jetpacklib.widget.YcTextWatcher

class MainHomeSearchActivity :
    BaseActivity<HomeSearchActivityBinding>(HomeSearchActivityBinding::inflate) {
    private val mViewModel: MainHomeVM by ycViewModels()
    private lateinit var mHistorySearchAdapter: TagAdapter<String?>
    private lateinit var mHotSearchAdapter: TagAdapter<String?>
    private var mHistoryValues: ArrayList<String> = ArrayList()
    private var mHotValues: ArrayList<String> = ArrayList()
    private val mHistoryTagNum = 5//历史记录标签个数
    private val mDao: SearchHistoryDao by lazy {
        RoomData.getDataBase(this).getSearchHistoryDao()
    }

    companion object {
        fun newInstance(context: Context) {
            val intent = Intent(context, MainHomeSearchActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun HomeSearchActivityBinding.initView() {

        tvCancel.setOnClickListener {
            if (groupHistory.isShown)
                finish()
            else {
                groupHistory.visibility = View.VISIBLE
                groupResult.visibility = View.GONE
            }
        }
        etSearch.apply {
            addTextChangedListener(object : YcTextWatcher() {
                override fun afterTextChanged(s: Editable?) {
                    if (s?.isEmpty() == true) {
                        ivSearchDelete.visibility = View.GONE
                    } else {
                        ivSearchDelete.visibility = View.VISIBLE
                    }
                }
            })
            setOnEditorActionListener(TextView.OnEditorActionListener { _: TextView?, actionId: Int, _: KeyEvent? ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    getData()
                    return@OnEditorActionListener true
                }
                false
            })
            ivSearchDelete.setOnClickListener {
                setText("")
            }
        }
        initHistorySearch()
        initHotSearch()
        initSearchResult()
        mViewModel.mGetHotSearch.observe {
            it.doSuccess { mList ->
                if (mList.ycIsNotEmpty()) {
                    mHotValues.clear()
                    for (item in mList!!) {
                        mHotValues.add(item.keyName.ycToNoEmpty())
                    }
                    mHotSearchAdapter.notifyDataChanged()
                }

            }.ycShowNetError()
        }
        ivHistorySearchClear.setOnClickListener {
            mHistoryValues.clear()
            mHistorySearchAdapter.notifyDataChanged()
        }
        getHistorySearch()
        mViewModel.getHotSearch()
    }

    fun HomeSearchActivityBinding.initHistorySearch() {
        tflHistorySearch.apply {
            mHistorySearchAdapter = object : TagAdapter<String?>() {
                override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
                    val tv = LayoutInflater.from(this@MainHomeSearchActivity)
                        .inflate(
                            R.layout.common_tag_history_item,
                            tflHistorySearch,
                            false
                        ) as TextView
                    tv.text = t
                    return tv
                }
            }
            adapter = mHistorySearchAdapter
            mHistorySearchAdapter.mTagDatas = mHistoryValues
            setMaxSelectCount(1)
            setCount(mHistoryTagNum)
            setIsShowMaxCount(true)
            setOnTagClickListener { view, position, parent ->
                etSearch.setText(mHistoryValues[position])
                getData()
                true
            }
        }
    }

    fun HomeSearchActivityBinding.initHotSearch() {
        tflHotHistorySearch.apply {
            mHotSearchAdapter = object : TagAdapter<String?>() {
                override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
                    val tv = LayoutInflater.from(this@MainHomeSearchActivity)
                        .inflate(
                            R.layout.common_tag_history_item,
                            tflHotHistorySearch,
                            false
                        ) as TextView
                    tv.text = t
                    return tv
                }
            }
            adapter = mHotSearchAdapter
            mHotSearchAdapter.mTagDatas = mHotValues
            setMaxSelectCount(1)
            setCount(mHistoryTagNum)
            setIsShowMaxCount(true)
            setOnTagClickListener { view, position, parent ->
                etSearch.setText(mHotValues[position])
                getData()
                true
            }
        }
    }

    fun HomeSearchActivityBinding.initSearchResult() {
        val viewPagerAdapter = YcViewPagerAdapter(
            mutableListOf(
                SearchResultFragment(TopicType.Type.TOPIC),
                SearchResultFragment(TopicType.Type.EXAM)
            ), this@MainHomeSearchActivity
        )

        viewPagerSearchResult.adapter = viewPagerAdapter
        TabLayoutMediator(tabLayoutSearchResult, viewPagerSearchResult) { tab, position ->
            tab.text = mutableListOf("专题", "考试")[position]
        }.attach()
    }

     private fun HomeSearchActivityBinding.getData() {
        groupHistory.visibility = View.GONE
        groupResult.visibility = View.VISIBLE
        addSearchHistory(etSearch.text.toString())
        mViewModel.search(etSearch.text.toString())
    }

    private fun getHistorySearch() {
        for (item in mDao.getSearchHistoryTable(UserInfoDataStoreKey.KEY_USER_NAME.name)) {
            mHistoryValues.add(item.name)
        }
        mHistorySearchAdapter.notifyDataChanged()
    }

    //新增搜索历史-后面需要添加数据库
    private fun addSearchHistory(searchName: String) {
        if (mHistoryValues.contains(searchName)) {
            mHistoryValues.remove(searchName)
        }
        if (searchName.isNotEmpty()) {
            mHistoryValues.add(0, searchName)
        }
        mHistorySearchAdapter.notifyDataChanged()
    }

    override fun onDestroy() {
        launch {
            mDao.delete()
            val dataArray: ArrayList<SearchHistoryTable> = ArrayList()
            for (item in 0 until if (mHistoryValues.size < mHistoryTagNum) mHistoryValues.size else mHistoryTagNum) {
                dataArray.add(SearchHistoryTable(name = mHistoryValues[item],acount = UserInfoDataStoreKey.KEY_USER_NAME.name))
            }
            mDao.insert(*dataArray.toTypedArray())
        }
        super.onDestroy()
    }
}
